<template>
  <div class="bgc-default pad-20">
    <div class="bg-color-white pad-20">
      <div class="tabs-box mar-t--10">
        <el-tabs v-model="tabActiveStatus" @tab-click="doChangeTab">
          <el-tab-pane :label="labels[97]" name="97"> </el-tab-pane>
          <el-tab-pane :label="labels[1]" name="1"> </el-tab-pane>
          <el-tab-pane :label="labels[20]" name="20"> </el-tab-pane>
          <el-tab-pane :label="labels[2]" name="2"> </el-tab-pane>
          <el-tab-pane :label="labels[4]" name="4"> </el-tab-pane>
          <el-tab-pane :label="labels[5]" name="5"> </el-tab-pane>
          <el-tab-pane :label="labels[100]" name="100"></el-tab-pane>
        </el-tabs>
      </div>
      <!--顶部搜索 -->
      <div class="top-operate-default flex-col" style="align-items: baseline; padding: 20px; height: 100%; ">
        <div>
          <label>搜索订单：</label>
          <el-select v-model="textCol" class="width-120">
            <el-option label="订单号" value="orderNo"></el-option>
            <template v-if="tabActiveStatus == 97">
              <el-option label="支付单号" value="payNo"></el-option>
              <el-option label="退款单号" value="refundPayNo"></el-option>
            </template>
            <el-option label="收货人" value="customerNickname"></el-option>
            <el-option label="收货人电话" value="customerPhone"></el-option>
            <el-option label="商品名称" value="goodsTitle"></el-option>
            <el-option label="经销商姓名" value="memberNickname"></el-option>
            <el-option label="经销商手机" value="memberPhone"></el-option>
            <el-option label="外部订单号" value="externalOrderNo"></el-option>
            <el-option label="店铺名称" value="shopName"></el-option>
          </el-select>
          <el-input v-model="textValue" placeholder="请输入内容" class="width-200"></el-input>

          <label class="mar-l-20">订单类型：</label>
          <el-select class="width-140" v-model="defaultQuery.orderType" placeholder="订单类型" clearable>
            <template v-for="(val, key) in dict.orderType">
              <el-option v-if="key == '33' || key == '36'"  :key="key" :label="val" :value="key"></el-option>
            </template>
          </el-select>

          <label class="mar-l-20">时间筛选：</label>
          <el-select class="width-120" v-model="timeCol" clearable>
            <el-option label="生成时间" value="createTime"></el-option>
            <el-option label="发货时间" value="deliveryTime"></el-option>
            <el-option label="完成时间" value="completeTime"></el-option>
          </el-select>
          <el-date-picker v-model="timeValue"
            type="daterange"
            range-separator="至"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </div>
        
        <div class="mar-t-10">
          <label>发货方：</label>
          <el-select v-model="defaultQuery.apartOrderSource" placeholder="订单发货方" class="width-140" clearable>
            <el-option label="需要企业发货" value="10"></el-option>
            <el-option label="供应商发货" value="20"></el-option>
            <el-option label="供货联盟发货" value="40"></el-option>
          </el-select>

          <label class="mar-l-20">平台类型：</label>
          <el-select v-model="defaultQuery.externalPlatformType" placeholder="平台类型" class="width-100" @change="changePlatformType">
            <el-option label="全部" value=""></el-option>
            <el-option v-for="(val, key) in dict.platformType" :key="key" :label="val" :value="key"></el-option>
          </el-select>
          <el-select v-model="defaultQuery.externalShopId" placeholder="店铺" class="width-160">
            <el-option v-for="(item, index) in shopList" :key="index" :label="item.shopName" :value="item.shopId"></el-option>
          </el-select>

          <el-button-group class="mar-l-20">
            <el-button type="primary" @click="doSearch">查询</el-button>
            <el-button @click="doResetSearch">重置</el-button>
          </el-button-group>
        </div>
      </div>

      <div class="pad-t-10">
        <template v-if="!warehouseDeliverFlag">
          <el-button v-if="tabActiveStatus == 1 || tabActiveStatus == 20" @click="doBatchGenerateSend">批量生成发货单</el-button>
        </template>
      </div>

      <!-- 内容列表 -->
      <div class="table-container mar-t-20">
        <el-table :data="dataList" @selection-change="handleSelectionChange" v-loading="listLoading" element-loading-text="加载中">
          <el-table-column width="50px" type="selection"></el-table-column>
          <el-table-column min-width="260px" label="订单信息">
            <template slot-scope="scope">
              <div class="flex v-align-c">
                <label v-if="scope.row.goodsImageUrl"><img :src="scope.row.goodsImageUrl" class="t-goods-pic"></label>
                <div class="font-14 pad-l-10 line-2">
                  <span :title="scope.row.goodsTitle">{{ scope.row.goodsTitle }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="260px" label="订单号">
            <template slot-scope="scope">
              <div v-if="scope.row.externalOrderNo">
                <span class="font-color-9">{{(dict.platformType[scope.row.externalPlatformType]||'') + scope.row.externalOrderNo}}</span>
              </div>
              <div><span class="font-color-9">系统：</span>{{scope.row.orderNo}}</div>
            </template>
          </el-table-column>
          <el-table-column width="80px" label="售后状态" align="center">
            <template slot-scope="scope">
              <div>
                <template v-if="scope.row.afterSaleFlag == 0">
                  <span class="font-color">{{dict.afterSaleFlag[scope.row.afterSaleFlag]}}</span>
                </template>
                <template v-else>
                  <span v-if="scope.row.orderNo" class="font-red cursor-p" @click="doLinkAfter(scope.row)">{{dict.afterSaleFlag[scope.row.afterSaleFlag]}}</span>
                  <span v-else class="font-red">{{dict.afterSaleFlag[scope.row.afterSaleFlag]}}</span>
                </template>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="240px" label="支付单号/退款单号" v-if="tabActiveStatus == 97">
            <template slot-scope="scope">
              <div class="line-h-14">
                <div><span class="font-color-9">支付单：</span>{{scope.row.payNo}}</div>
                <div><span class="font-color-9">退款单：</span>{{scope.row.refundPayNo}}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="140px" label="授信方式" align="center" v-if="tabActiveStatus == 97">
            <template slot-scope="scope">
              {{ dict.creditType[scope.row.creditTypeSnapshot] }}
            </template>
          </el-table-column>
          <el-table-column width="140px" label="订单状态" align="center">
            <template slot-scope="scope">
              {{ dict.orderStatus[scope.row.orderStatus] }}
            </template>
          </el-table-column>
          <el-table-column width="140px" label="授信支付状态" align="center">
            <template slot-scope="scope">
              {{ dict.weikeOrderNeedPay[scope.row.weikeOrderNeedPay] }}
            </template>
          </el-table-column>
          <el-table-column width="150px" label="收货人" >
            <template slot-scope="scope">
              <div>{{scope.row.customerNickname}}</div>
              <div v-if="scope.row.customerPhone">{{scope.row.customerPhone}}</div>
            </template>
          </el-table-column>
          <el-table-column width="150px" label="经销商" >
            <template slot-scope="scope">
              <div v-if="scope.row.memberNickname">
                <div>{{scope.row.memberNickname}}</div>
                <div v-if="scope.row.memberPhone">{{scope.row.memberPhone}}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="120px" label="商品数量" prop="goodsNum">
          </el-table-column>
          <el-table-column width="150px" label="零售金额">
            <template slot-scope="scope">
              <div>运费：￥{{ scope.row.freight }}</div>
              <div>商品：￥{{ (scope.row.orderPrice - scope.row.freight).toFixed(2) }}</div>
              <div class="font-blue">合计：￥{{ scope.row.orderPrice }}</div>
            </template>
          </el-table-column>
          <el-table-column width="150px" label="分销金额">
            <template slot-scope="scope">
              <div><span class="font-color-9">运费：</span>￥{{scope.row.orderFreightToThird||0}}</div>
              <div><span class="font-color-9">商品：</span>￥{{((scope.row.orderAmountToThird||0)-(scope.row.orderFreightToThird||0)).toFixed(2)}}</div>
              <div><span class="font-color-9">合计：</span>￥{{scope.row.orderAmountToThird||0}}</div>
            </template>
          </el-table-column>
          <el-table-column width="200px" label="时间" align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.createTime">生成：{{ scope.row.createTime }}</div>
              <div v-if="scope.row.payTime">付款：{{ scope.row.payTime }}</div>
              <div v-if="scope.row.deliveryTime">发货：{{ scope.row.deliveryTime }}</div>
              <div v-if="scope.row.receivedTime">收货：{{ scope.row.receivedTime }}</div>
              <div v-if="scope.row.completeTime">完成：{{ scope.row.completeTime }}</div>
              <div v-if="scope.row.cancelTime">取消：{{ scope.row.cancelTime }}</div>
            </template>
          </el-table-column>
          <el-table-column width="120px" label="包裹数量" prop="packageNum">
          </el-table-column>
          <el-table-column width="90px" label="操作" align="right" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="medium" class="table-btn" @click="doLinkDetail(scope.row)">查看详情</el-button>
              <template v-if="tabActiveStatus != '97'">
                <template v-if="!warehouseDeliverFlag">
                  <el-button type="text" size="medium" class="table-btn" v-if="scope.row.enterpriseDeliveryFlag == 1" @click="doOpenDeliver(scope.row)">发货</el-button>
                </template>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 发货单管理dialog -->
    <el-dialog width="1200px" v-el-drag-dialog title="发货单管理" :visible.sync="orderDeliverVisible" :show-close="false">
      <order-send-manage :showFlag="orderDeliverVisible"
        :apartOrderId="selectApartOrderId"
        @callback="doCallbackOrderDeliver">
      </order-send-manage>
    </el-dialog>

  </div>
</template>

<script>
  import { pageProjectOrder, statProjectOrder } from '@/api/goods/order'
  import { listThirdShop } from '@/api/user/third-shop'
  import { getDictByGroupName } from '@/api/common/common'
  import { getByEnterpriseId } from '@/api/user/enterprise'
  import orderSendManage from '@/views/goods/order/components/order-send-manage'
  import elDragDialog from '@/directive/el-dragDialog'

  export default {
    components: { orderSendManage },
    directives: {
      elDragDialog
    },
    data() {
      return {
        labels: {
          '97': '授信待支付(0)',
          '1': '待发货(0)',
          '20': '部分发货(0)',
          '2': '已发货(0)',
          '4': '已完成(0)',
          '5': '已取消(0)',
          '100': '全部已付款订单(0)'
        },
        // tab model
        tabActiveStatus: '97',
        // 文本model
        textCol: 'orderNo',
        textValue: '',
        // 时间model
        timeCol: 'createTime',
        timeValue: [],
        // 查询表单
        searchListQuery: {},
        // 默认查询表单
        defaultQuery: {
          currentPage: 1,
          size: 10,
          enterpriseId: '',
          memberId: '',
          memberIdIsNotNull: '1',
          orderTypes: '36,33',
          orderStatus: '',
          externalPlatformType: '',
          externalShopId: '',
          apartOrderSource: ''
        },
        // 数据字典
        dict: {
          platformType: {},
          afterSaleFlag: {},
          orderStatus: {},
          creditType: {}
        },
        // 发票管理页面跳转参数
        invoiceManagement: {
          // pageSource： 0-申请开票页面；1-平台开票页面
          pageSource: '',
          // buttonType：1-待审核金额详情; 2-已开票金额详情；
          buttonType: ''
        },
        // 店铺集合
        shopList: [],
        // 选择订单id
        selectApartOrderId: '',
        // 订单发货visible
        orderDeliverVisible: false,
        // 仓库发货flag
        warehouseDeliverFlag: false,
        total: 0,
        listLoading: false,
        dataList: [],
        multipleSelection: []
      }
    },
    // 初始化页面
    created() {
      this.searchListQuery = { ...this.defaultQuery }
      getByEnterpriseId(this.getEnterpriseId()).then(response => {
        this.enterpriseConfig = response.data
        this.warehouseDeliverFlag = this.enterpriseConfig.warehouseAuthority === 1 && this.enterpriseConfig.warehouseDeliverFlag === 1
      })
      getDictByGroupName('ThirdOrderDTO').then(response => {
        Object.assign(this.dict, response.data)
      })
      const query = this.getCurrentPage().query
      if (query.pageSource && query.buttonType) {
        this.invoiceManagement.pageSource = query.pageSource
        this.invoiceManagement.buttonType = query.buttonType
        this.tabActiveStatus = '4'
      }
      this.initStat()
      this.initList()
    },
    methods: {
      // tab切换事件
      doChangeTab() {
        this.doResetSearch()
        this.initStat()
      },
      // 初始化
      initList() {
        this.listLoading = true
        this.setSearchListQuery()
        pageProjectOrder(this.searchListQuery).then(response => {
          this.listLoading = false
          if (response.isError) return
          this.total = response.data.total
          this.dataList = response.data.records
          Object.assign(this.dict, response.data.dict)
        })
      },
      // 统计事件
      initStat() {
        this.setSearchListQuery()
        statProjectOrder(this.searchListQuery).then(response => {
          if (response.isError) return
          this.labels[97] = '授信待支付(' + response.data[97] + ')'
          this.labels[1] = '待发货(' + response.data[1] + ')'
          this.labels[20] = '部分发货(' + response.data[20] + ')'
          this.labels[2] = '已发货(' + (response.data[2]) + ')'
          this.labels[4] = '已完成(' + (response.data[4]) + ')'
          this.labels[5] = '已取消(' + (response.data[-1] + response.data[-2]) + ')'
          const total = (response.data[100])
          this.labels[100] = '全部已付款订单(' + (total - response.data[0] - response.data[-1] - response.data[-10]) + ')'
        })
      },
      setSearchListQuery() {
        const size = this.searchListQuery.size
        const currentPage = this.searchListQuery.currentPage
        this.searchListQuery = { ... this.defaultQuery }
        this.searchListQuery.size = size
        this.searchListQuery.currentPage = currentPage
        this.searchListQuery[this.textCol] = this.textValue
        this.searchListQuery.dateColumn = this.timeCol
        this.searchListQuery.startDate = (this.timeValue && this.timeValue.length > 0) ? this.timeValue[0] : ''
        this.searchListQuery.endDate = (this.timeValue && this.timeValue.length > 1) ? this.timeValue[1] : ''
        this.searchListQuery.enterpriseId = this.getEnterpriseId()
        this.searchListQuery.memberId = this.getMemberId()
        this.searchListQuery.pageSource = this.invoiceManagement.pageSource
        this.searchListQuery.buttonType = this.invoiceManagement.buttonType
        switch (this.tabActiveStatus * 1) {
          case 97:
            this.searchListQuery.orderStatus = '97'
            this.searchListQuery.weikeOrderNeedPay = 1
            break
          case 100:
            this.searchListQuery.orderStatus = ''
            this.searchListQuery.orderStatusList = '1,20,2,3,4'
            break
          default:
            this.searchListQuery.orderStatus = this.tabActiveStatus
        }
        if (this.searchListQuery.orderType) {
          this.searchListQuery.orderTypes = ''
        } else {
          this.searchListQuery.orderTypes = '36,33'
        }
      },
      // 查看详情事件
      doLinkDetail(row) {
        this.$router.push({ path: '/order/order/detail/index', query: { orderId: row.orderId, memberId: row.memberId, shareMemberId: !row.shareMemberId ? '' : row.shareMemberId }})
      },
      // 批量生成发货单事件
      doBatchGenerateSend() {
        if (this.multipleSelection.length <= 0) {
          this.$message({ message: '请勾选数据', type: 'warning' })
          return
        }
        const params = {
          enterpriseId: this.getEnterpriseId(),
          systemRoleType: this.getSystemRoleType(),
          orderIds: this.multipleSelection.map(item => item.orderId)
        }
        this.$bus.$emit('asyncHandle', '300003', params, () => {
          this.initList()
        })
      },
      // 打开发货dialog事件
      doOpenDeliver(row) {
        this.selectApartOrderId = row.apartOrderId
        this.orderDeliverVisible = true
      },
      // 订单发货回调事件
      doCallbackOrderDeliver(callbackFlag) {
        if (callbackFlag) {
          this.initList()
        }
        this.orderDeliverVisible = false
      },
      // 查询事件
      doSearch() {
        this.searchListQuery.currentPage = 1
        this.initList()
      },
      // 重置事件
      doResetSearch() {
        const originData = this.$options.data()
        this.textCol = originData.textCol
        this.textValue = originData.textValue
        this.timeCol = originData.timeCol
        this.timeValue = originData.timeValue
        this.defaultQuery = originData.defaultQuery
        this.invoiceManagement = originData.invoiceManagement
        this.doSearch()
      },
      changePlatformType() {
        const params = {
          enterpriseId: this.getEnterpriseId(),
          platformType: this.defaultQuery.externalPlatformType
        }
        listThirdShop(params).then(response => {
          if (response.isError) return
          this.shopList = response.data
          this.thirdOrder.thirdShopId = ''
        })
      },
      // 查看售后事件
      doLinkAfter(row) {
        const routeData = this.$router.resolve({
          path: '/order/after-sale/list',
          query: { orderNo: row.orderNo }
        })
        window.open(routeData.href, '_blank')
      },
      // 勾选事件
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initList()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initList()
      }
    }
  }
</script>

<style lang="less" scoped>

</style>
